<?php

namespace App\Http\Traits;

use App\Models\User;
use Auth;

trait UserTrait
{
    /**
     * @param \SocialiteProviders\Manager\OAuth2\User $user gitlab oauth user info
     * @param string                                  $access_token
     *
     * @return User
     */
    public function touchUser($user, $access_token = '')
    {
        $user_data = [
            'gitlab_nickname' => $user['username'],
            'gitlab_avatar'   => $user['avatar_url'],
            // gitlab api v4 去掉了 is_admin 字段。2017年05月24日13:31:06
            //            'gitlab_is_admin'     => $user['is_admin'],
            'gitlab_uid'          => $user['id'],
            'name'                => $user['name'],
            'email'               => $user['email'],
            'gitlab_access_token' => $access_token,
        ];

        if (isset($user['private_token'])) {
            $user_data['gitlab_private_token'] = $user['private_token'];
        }

        /** @var User $user_model */
        $user_model = User::updateOrCreate([
            'gitlab_uid' => $user['id'],
        ], $user_data);

        return $user_model;
    }

    public function loginUsingId($user_id)
    {
        Auth::loginUsingId($user_id);
    }
}
